package com.t2t.top.ha;

import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.Arrays;

public class DataMonitor implements Watcher, StatCallback {
    ZooKeeper zk;
    String znode;
    String filename;
    boolean dead;
    RedisThread redisThread = new RedisThread();
    DataMonitorListener listener;

    byte prevData[];

    public DataMonitor(ZooKeeper zk, String znode, DataMonitorListener listener,String  filename) {
        this.zk = zk;
        this.znode = znode;
        this.listener = listener;
        this.filename = filename;
        zk.exists(znode, true, this, null);
    }

	public void process(WatchedEvent event) {
		String path = event.getPath();
		System.out.println(path);
		if (event.getType() == Event.EventType.None) {
			switch (event.getState()) {
			case SyncConnected:
				break;
			case Expired:
				dead = true;
				listener.closing(KeeperException.Code.SessionExpired);
				break;
			}
		}else {
			if (path != null && path.equals(znode)) {
				ZooKeeper zk2 = zk;
				zk2.exists(znode, true, this, null);
			}
		}
	}

    public void processResult(int rc, String path, Object ctx, Stat stat) {
        boolean exists;
        switch (rc) {
        case Code.Ok:
            exists = true;
            break;
        case Code.NoNode:
            exists = false;
            break;
        case Code.SessionExpired:
        case Code.NoAuth:
            dead = true;
            listener.closing(rc);
            return;
        default:
            zk.exists(znode, true, this, null);
            return;
        }
        try {
			redisThread.setMasterIP(new String(zk.getData("/zk/master", false, null), "utf-8").split(":")[0]);
			redisThread.setSlaveIP(new String(zk.getData("/zk/slave", false, null), "utf-8"));
			redisThread.setPath(path);
			redisThread.setFilename(filename);
			redisThread.setZk(zk);
		} catch (Exception e1) {
			e1.printStackTrace();
		} 
    	redisThread.start();
        byte b[] = null;
        if (exists) {
            try {
                b = zk.getData(znode, false, null);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                return;
            }
        }
        if ((b == null && b != prevData)
                || (b != null && !Arrays.equals(prevData, b))) {
            listener.exists(b);
            prevData = b;
        }
    }
}